﻿namespace System.Data.Entity.Infrastructure.Annotations
{
    using System;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Infrastructure;
    using System.Linq;
    using System.Text;
    using System.Text.RegularExpressions;

    public class FullTextIndexedTableAnnotationSerializer : IMetadataAnnotationSerializer
    {
        private static readonly Regex _fullTextIndexedTablePartsSplitter
           = new Regex(@"(?<!\\),", RegexOptions.Compiled);

        public string Serialize(string name, object value)
        {
            var annotation = value as FullTextIndexedTableAnnotation;

            var stringBuilder = new StringBuilder();

            stringBuilder.Append(SerializeFullTextIndexedTableAttribute(annotation.FullTextIndexedTable));

            return stringBuilder.ToString();
        }

        internal static string SerializeFullTextIndexedTableAttribute(FullTextIndexedTableAttribute fullTextIndexedTableAttribute)
        {
            var builder = new StringBuilder("{ ");

            builder
                .Append("Name: ")
                .Append(
                    fullTextIndexedTableAttribute.Name
                        .Replace(",", @"\,")
                        .Replace("{", @"\{"));

            builder.Append(" }");

            return builder.ToString();
        }

        public object Deserialize(string name, string value)
        {
            value = value.Trim();

            value = value.Substring(1);
            value = value.Substring(0, value.Length - 1);

            // TODO: rework
            FullTextIndexedTableAttribute fullTextIndexedTableAttribute = null;

            foreach (var fullTextIndexedTablePart in _fullTextIndexedTablePartsSplitter.Split(value).Select(s => s.Trim()))
            {
                if (fullTextIndexedTablePart.StartsWith("Name:", StringComparison.Ordinal))
                {
                    var fullTextIndexedTableName = fullTextIndexedTablePart.Substring(5).Trim();

                    fullTextIndexedTableAttribute = new FullTextIndexedTableAttribute(fullTextIndexedTableName.Replace(@"\,", ",").Replace(@"\{", "{"));
                }
            }

            return new FullTextIndexedTableAnnotation(fullTextIndexedTableAttribute);
        }
    }
}
